package com.ruoyi.common.utils;

import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.ruoyi.common.utils.bean.DateAddEntity;
import com.ruoyi.common.utils.bean.DateCount;
import org.apache.commons.lang3.time.DateFormatUtils;

/**
 * 时间工具类
 * 
 * @author ruoyi
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils
{
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDD = "yyyyMMdd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String HH_MM_ss = "HH:mm:ss";

    public static String HHMMss = "HHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", 
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    private static final String DEFAULT_DATA = "yyyy-MM";

    public static final String YEAR_TYPE = "year";

    public static final String MONTH_TYPE = "month";
    public static Pattern pattern = Pattern.compile("[0-9]*");




    /**
     * 获取当前Date型日期
     * 
     * @return Date() 当前日期
     */
    public static Date getNowDate()
    {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     * 
     * @return String
     */
    public static String getDate()
    {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime()
    {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow()
    {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format)
    {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date)
    {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date)
    {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts)
    {
        try
        {
            return new SimpleDateFormat(format).parse(ts);
        }
        catch (ParseException e)
        {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str)
    {
        if (str == null)
        {
            return null;
        }
        try
        {
            return parseDate(str.toString(), parsePatterns);
        }
        catch (ParseException e)
        {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate()
    {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算相差天数
     */
    public static int differentDaysByMillisecond(Date date1, Date date2)
    {
        return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24)));
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate)
    {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * 增加 LocalDateTime ==> Date
     */
    public static Date toDate(LocalDateTime temporalAccessor)
    {
        ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 增加 LocalDate ==> Date
     */
    public static Date toDate(LocalDate temporalAccessor)
    {
        LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
        ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }



    public static String formate(Date data, String pattern) {
        if (data != null) {
            return DateFormatUtils.format(data, pattern);
        }
        return "";
    }

    public static String Date2Str(Date date, String pattern) {
        SimpleDateFormat time = new SimpleDateFormat(pattern);
        return time.format(date);
    }




    public static String formate(Date data) {
        Calendar c = Calendar.getInstance();
        c.setTime(data);
        return c.get(1) + "年" + (c.get(2) + 1) + "月" + c.get(5) + "日";
    }











    public static DateAddEntity getAfterAddDate(String dateStr, String addYearOrMonth, String addNum) {
        DateAddEntity entity = new DateAddEntity();
        if (valiDate(dateStr)) {
            Date date = null;
            date = getDateFromDateStr(dateStr);
            return getAfterAddDate(date, addYearOrMonth, addNum);
        }
        try {
            throw new Exception("传入的格式不正确");
        } catch (Exception e) {
            e.printStackTrace();


            return entity;
        }
    }

    public static DateCount getDateYearAndMonth(Date date) {
        DateCount entity = new DateCount();
        Calendar instance = Calendar.getInstance();
        instance.setTime(date);
        entity.setYear(Integer.valueOf(instance.get(1)));
        entity.setMonth(Integer.valueOf(getNowMonth(instance.get(2))));
        return entity;
    }

    public static String getYearWithMonth(Date date) {
        Calendar instance = Calendar.getInstance();
        instance.setTime(date);
        int month = getNowMonth(instance.get(2));
        String monthStr = "";
        if (month >= 10) {
            monthStr = month + "";
        } else {
            monthStr = "0" + month;
        }
        return instance.get(1) + "" + monthStr;
    }










    public static DateAddEntity getAfterAddDate(Date date, String addYearOrMonth, String addNum) {
        DateAddEntity entity = new DateAddEntity();

        try {
            String year = getYear(date);
            String month = getMonth(date);

            DateCount dateEntity = new DateCount();
            if (StringUtils.isNotBlank(addYearOrMonth)) {
                dateEntity.setAddYearOrMonth(addYearOrMonth);
            }
            if (StringUtils.isNotBlank(addNum)) {
                dateEntity.setAddNum(addNum);
            }
            dateEntity.setYear(Integer.valueOf(Integer.parseInt(year)));
            dateEntity.setMonth(Integer.valueOf(Integer.parseInt(month)));
            dateEntity.setYearMonthDate(date);
            entity = getDateCountList(dateEntity);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return entity;
    }

    public static DateAddEntity getDateDif(Date date, Date date1) {
        DateAddEntity entity = new DateAddEntity();













        Calendar start = Calendar.getInstance();
        Calendar end = Calendar.getInstance();
        start.setTime(date);
        end.setTime(date1);

        int result = end.get(1) * 12 + end.get(2) - start.get(1) * 12 - start.get(2);

        if (result < 0) {
            result = 0;
            entity.setDateCountNum(0);
        } else {
            entity.setDateCountNum(result / 12);
        }
        entity.setMonthNum(result);
        return entity;
    }


    private static int getNowMonth(int i) {
        return i + 1;
    }

    public static DateAddEntity getAfterAddMonth(Date date) {
        return getAfterAddDate(date, "month", "0");
    }


    public static DateAddEntity getAfterAddYear(Date date) {
        return getAfterAddDate(date, "year", "0");
    }


    public static int getMonthCount(Date start, Date end) {
        Calendar can = Calendar.getInstance();
        can.setTime(start);
        int count = 0;
        while (can.getTime().before(end)) {
            can.add(2, 1);
            count++;
        }
        return count;
    }








    private static DateAddEntity getDateCountList(DateCount dateCount) throws ParseException {
        DateAddEntity entity = new DateAddEntity();
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        String nowDate = sdf.format(date);
        Integer nowYear = Integer.valueOf(Integer.parseInt(getYear(date)));
        Integer nowMonth = Integer.valueOf(Integer.parseInt(getMonth(date)));
        Date start = dateCount.getYearMonthDate();
        Date end = sdf.parse(nowDate);
        Calendar can = Calendar.getInstance();

        can.setTime(start);
        int monthCount = 0;
        Integer dateCountYear = dateCount.getYear();
        Integer dateCountMonth = dateCount.getMonth();
        List<DateCount> list = new ArrayList<>();
        while (can.getTime().before(end)) {


            Integer month = Integer.valueOf(Integer.parseInt(getMonth(can.getTime())));

            if (month == dateCountMonth) {
                DateCount dateEntity = getDateCountEntity(can);
                if (StringUtils.isNotBlank(dateCount.getAddYearOrMonth()) && StringUtils.isNotBlank(dateCount.getAddNum())) {

                    DateCount dateCountAfterAdd = getDateCountAfterAdd(dateEntity, dateCount.getAddYearOrMonth(), dateCount.getAddNum());
                    dateEntity.setAfterAddDateCount(dateCountAfterAdd);
                }
                list.add(dateEntity);
            }

            can.add(2, 1);
            monthCount++;
        }
        if (dateCountMonth.intValue() > nowMonth.intValue()) {
            DateCount dateEntity = new DateCount();
            dateEntity.setYear(nowYear);
            dateEntity.setMonth(nowMonth);
            dateEntity.setYearMonthDate(sdf.parse(nowYear + "-" + nowMonth));
            DateCount dateCountAfterAdd = getDateCountAfterAdd(dateEntity, dateCount.getAddYearOrMonth(), dateCount.getAddNum());
            dateEntity.setAfterAddDateCount(dateCountAfterAdd);
            list.add(dateEntity);
        }
        entity.setDateCountList(list);
        entity.setDateCountNum(list.size());

        entity.setMonthNum(getNowMonth(monthCount));
        return entity;
    }










    private static DateCount getDateCountAfterAdd(DateCount dateCount, String type, String addNum) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        DateCount dateEntity = new DateCount();
        Calendar can = Calendar.getInstance();
        can.setTime(dateCount.getYearMonthDate());
        if (("1".equals(type) || "2".equals(type)) &&
                Integer.parseInt(addNum) != 0) {
            switch (Integer.parseInt(type)) {
                case 1:
                    can.add(1, Integer.parseInt(addNum));
                    dateEntity = getDateCountEntity(can);
                    return dateEntity;
                case 2:
                    can.add(2, Integer.parseInt(addNum));
                    dateEntity = getDateCountEntity(can);
                    return dateEntity;
            }

        }
        return null;
    }







    private static DateCount getDateCountEntity(Calendar can) {
        DateCount dateEntity = new DateCount();
        Integer year = Integer.valueOf(Integer.parseInt(getYear(can.getTime())));
        Integer month = Integer.valueOf(Integer.parseInt(getMonth(can.getTime())));
        dateEntity.setYear(year);
        dateEntity.setMonth(month);
        dateEntity.setYearMonthDate(can.getTime());
        return dateEntity;
    }





    public static String formatDate(Date date, Object... pattern) {
        String formatDate = null;
        if (pattern != null && pattern.length > 0) {
            formatDate = DateFormatUtils.format(date, pattern[0].toString());
        } else {
            formatDate = DateFormatUtils.format(date, "yyyy-MM-dd");
        }
        return formatDate;
    }





    public static String getYear(Date date) {
        return formatDate(date, new Object[] { "yyyy" });
    }




    public static String getMonth(Date date) {
        return formatDate(date, new Object[] { "MM" });
    }

    public static String getDay(Date date) {
        return formatDate(date, new Object[] { "dd" });
    }

    public static String getDate(String pattern) {
        return DateFormatUtils.format(new Date(), pattern);
    }

    public static String getTodayYMD() {
        return getToday("yyyy-MM-dd");
    }
    public static String getToday(String format) {
        Date date = new Date();
        SimpleDateFormat sd = new SimpleDateFormat(format);
        return sd.format(date);
    }







    public static int getMaxDayByYearMonth(int year, int month) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(1, year - 1);
        calendar.set(2, month);
        return calendar.getActualMaximum(5);
    }




    public static boolean isNotNull(String dateStr) {
        if (StringUtils.isBlank(dateStr)) {
            return false;
        }
        return true;
    }








    public static boolean isCorrectFormat(String dateStr) {
        if (StringUtils.isBlank(dateStr)) {
            return false;
        }
        Matcher isNum = pattern.matcher(dateStr);
        if (isNotNull(dateStr) && isNum.matches() && (dateStr.length() == 8 || dateStr.length() == 6)) {
            int month = Integer.parseInt(dateStr.substring(4, 6));
            if (month > 12) {
                return false;
            }
            return true;
        }
        return false;
    }

    public static Date toParse(String str) {
        if (isCorrectFormat(str)) {
            return parseDate(str);
        }
        return null;
    }


    public static boolean valiDate(Object dateStr) {
        Date data = parseDate(dateStr);
        if (data != null) {
            return true;
        }
        return false;
    }

    public static Date getDateFromDateStr(String dateStr) {
        SimpleDateFormat sdf = null;
        for (int i = 0; i < parsePatterns.length; i++) {
            sdf = new SimpleDateFormat(parsePatterns[i]);
            try {
                Date date = sdf.parse(dateStr);
                return date;
            } catch (ParseException e) {}
        }



        return null;
    }

    public static Date format(String str, String partten) {
        SimpleDateFormat sdf = new SimpleDateFormat(partten);
        try {
            Date date = sdf.parse(str);
            return date;
        } catch (ParseException e) {
            return null;
        }
    }





    public static int differentDays(String str1, String str2) {
        return differentDays(parseDate(str1), parseDate(str2));
    }








    public static int differentDays(Date date1, Date date2) {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);

        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        int day1 = cal1.get(6);
        int day2 = cal2.get(6);

        int year1 = cal1.get(1);
        int year2 = cal2.get(1);
        if (year2 < year1) {
            return 0;
        }
        if (year2 == year1 && day2 < day1) {
            return 0;
        }
        if (year1 != year2) {

            int timeDistance = 0;
            for (int i = year1; i < year2; i++) {
                if ((i % 4 == 0 && i % 100 != 0) || i % 400 == 0) {

                    timeDistance += 366;
                } else {

                    timeDistance += 365;
                }
            }
            return timeDistance + day2 - day1;
        }


        return day2 - day1;
    }


    public static String getNowDateStr(long l, String partten) {
        Date time = new Date(l);
        String formate = formate(time, partten);
        return formate;
    }





    public static int daycomparePrecise(String fromDate, String toDate) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMM");
        String fd = fromDate;
        String td = toDate;
        Date date = formatter.parse(fd);
        Date date1 = formatter.parse(td);
        Calendar from = Calendar.getInstance();
        from.setTime(date);
        Calendar to = Calendar.getInstance();
        to.setTime(date1);

        int fromYear = from.get(1);
        int fromMonth = from.get(2);
        int toYear = to.get(1);
        int toMonth = to.get(2);
        int month = toYear * 12 + toMonth - fromYear * 12 + fromMonth;
        return Math.abs(month);
    }

    public static void main(String[] args) {
        formate(new Date());
    }
}
